<?php

namespace app\upgrade\model;

use app\upgrade\model\UpgradeFile;
use app\upgrade\model\UpgradeFromCloud;

class UpgradeVersion extends Base
{
    /**
     * 获取指定版本的新版本数据
     * @param  string $version 版本号
     * @param  string $branch  分知名
     * @author xuewl <master@xuewl.com>
     * @return array
     */
    public function version_compare($version, $branch, $lists = false)
    {
        if (!$version || !$branch) {
            $this->error = '版本号和分支名必填';
            return false;
        }
        // getFieldBy 内置方法
        $id = $this->getFieldByVersion($version, 'id');
        if ((int) $id < 1) {
            $this->error = '版本号非法';
            return false;
        }
        $sqlmap = array();
        $sqlmap[] = $lists ? ['id', "GT", $id] : ['id', "EQ", $id];
        $sqlmap[] = ['branch', "eq", $branch];
        $sqlmap[] = ['status', "eq", 1];
        $versions =  $this->field('branch, version, file_id, release, status, create_time')->where($sqlmap)->order("id ASC");
        $versions = $lists ? $versions->select() : $versions->find();
        if (!$versions) {
            $this->error = '没有找到版本数据';
            return false;
        }
        return $versions->append(['md5'])->toArray();
    }

    /**
     * 文件信息
     *
     * @param [type] $v
     * @param [type] $d
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getMd5Attr($v, $d)
    {
        return (new UpgradeFile)->where(['id' => $d['file_id']])->value('md5');
    }

    public function getStatusTextAttr($v, $d)
    {
        $arr = ['停用', '正常'];
        return $arr[$d['status']];
    }


    public function uploadVersion($_data)
    {
        if (empty($_data['file_id'])) {
            return $this->error('文件id不能为空！');
        }
        if (empty($_data['version'])) {
            return $this->error('版本号不能为空！');
        }
        $map = [];
        $map[] = ['branch', 'eq', $_data['branch']];
        // 获取上一版本号
        $last_version = $this->where($map)->order('id desc')->value('version');
        // 版本号比较
        if (version_compare($_data['version'], $last_version, '<=')) {
            $this->error = '同一版本类型，新版本号不得小于或等于上一版本，上一版本号为：' . $last_version;
            return false;
        }
        if ($this->allowField(true)->save($_data)) {
            return true;
        }
        return false;
    }


    /**
     * 通知更新
     *
     * @param [type] $data
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function noticeVersion($data, $all = true)
    {
        if ($all) {
            if (!$data['id']) {
                $this->error = 'id不能为空';
                return false;
            }
            $sqlmap = array();
            $sqlmap[] = ['id', "EQ", $data['id']];
            $sqlmap[] = ['status', "eq", 1];
            $version =  $this->field('branch, version, file_id')->where($sqlmap)->select();
            if (!$version) {
                $this->error = '未找到此版本信息或该版本已被停用';
                return false;
            }
            $version = $version->toArray();
            $upversion = array();
            foreach ($version as $v) {
                $upversion[$v['version']] = $v;
            }
        }
        $result['success'] = 0;
        $result['error'] = 0;
        // 查询站点状态为 正常1 统一版本控制1
        $shop_list = Shop::where(['status' => 1, 'common_control' => 1])->select();
        if ($data['shop_id']) {
            $shop_list = Shop::where([['id', 'in', $data['shop_id']]])->select();
        }
        $shop_list ? $shop_list = $shop_list->toArray() : $shop_list = [];
        if ($shop_list) {
            // 遍历站点通知
            foreach ($shop_list as $value) {
                if (($ret = $this->notifyShopSite($value['id'], $upversion))) {
                    $result['success']++;
                } else {
                    $result['error']++;
                }
            }
            if ($all) return "成功更新：{$result['success']}，失败：{$result['error']}";
            return $ret;
        }
        $this->error = '未找到匹配站点';
        return false;
    }
    /**
     * 执行更新并记录
     *
     * @param [type] $shop_id
     * @param [type] $version
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function notifyShopSite($shop_id, $version)
    {
        $_data['action'] = 'upgrade';
        $_data['data'] = $version;
        $result = Cloud::post($shop_id, $_data);
        if (UpgradeFromCloud::where(['shop_id' => $shop_id])->find()) {
            UpgradeFromCloud::where(['shop_id' => $shop_id])
                ->update([
                    'shop_id' => $shop_id,
                    'notify'  => $result['notify'] ? $result['notify'] : '',
                    'ctime' => time()
                ]);
            UpgradeFromCloud::where(['shop_id' => $shop_id])->setInc('update_number');
        } else {
            UpgradeFromCloud::insert([
                'shop_id' => $shop_id,
                'notify'  => $result['notify'] ? $result['notify'] : '',
                'ctime' => time()
            ]);
        }
        return $result;
    }
}
